<?php

namespace App\Admin\Controllers;

use App\Models\AiLog;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
use Slowlyo\OwlAdmin\Controllers\AdminController;

class HomeController extends AdminController
{
    public function index(): JsonResponse|JsonResource
    {
        $page = $this->basePage()->css($this->css())->body([
            amis()->Grid()->columns([
                $this->lineChart()->set('md', 8),
                amis()->Flex()->className('h-full')->items([
                    $this->clock(),
                    $this->codeView(),
                ])->direction('column'),
            ]),
        ]);
        /*
         amis()->Grid()->className('mb-1')->columns([
                $this->frameworkInfo()->set('md', 5),
                amis()->Flex()->items([
                    $this->pieChart(),
                    $this->cube(),
                ]),
            ]),
         */
        return $this->response()->success($page);
    }

    public function codeView()
    {
        $phpOs = PHP_OS;
        $phpVersion = PHP_VERSION;
        $version = DB::select('SELECT VERSION() AS version');
        $version = $version[0]->version;
        $sql = "SELECT table_schema 'db_name',
                   SUM(data_length + index_length) / 1024 / 1024 'db_size_mb'
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
            GROUP BY table_schema";
        $dbSize = DB::select($sql);
        $dbSize = round($dbSize[0]->db_size_mb,2);
        return amis()->Panel()->className('h-full clear-card-mb rounded-md')->body([
            amis()->html()->options(['html' => true, 'breaks' => true])->value(<<<MD
<table style="width: 100%">
<tr style="width: 100%;">
<th style="width: 110px">系统版本</th>
<td style="width: 60%">$phpOs / $phpVersion</td>
</tr>
<tr>
<th>服务器软件</th>
<td>{$_SERVER['SERVER_SOFTWARE']}</td>
</tr>
<tr>
<th>MySQL 版本</th>
<td>{$version}</td>
</tr>
<tr>
<th>数据库尺寸</th>
<td>{$dbSize}MB </td>
</tr>
</tbody>
</table>
MD
            ),
        ]);
    }

    public function clock()
    {
        /** @noinspection all */
        return amis()->Card()->className('h-full bg-blingbling mb-4')->header(['title' => '当前时间'])->body([
            amis()->Custom()
                ->name('clock')
                ->html('<div id="clock" class="text-4xl"></div><div id="clock-date" class="mt-5"></div>')
                ->onMount(<<<JS
const clock = document.getElementById('clock');
const tick = () => {
    clock.innerHTML = (new Date()).toLocaleTimeString();
    requestAnimationFrame(tick);
};
tick();

const clockDate = document.getElementById('clock-date');
clockDate.innerHTML = (new Date()).toLocaleDateString();
JS

                ),
        ]);
    }

    public function lineChart()
    {
        $start_day = Carbon::now()->addDays(-30)->format('Y-m-d');
        $list = AiLog::selectRaw('sum(image_token) as image_token, sum(text_token) as text_token, model, DATE(created_at) AS day')
            ->where('created_at','>=',$start_day)
            ->groupBy('model', DB::raw('DATE(created_at)'))
            ->orderBy('day')
            ->get()
            ->toArray();
        $days = array_unique(array_column($list,'day'));
        $images = $maxs = $plus = [];
        foreach ($list as $item){
            if(!isset($images[$item['day']])){
                $images[$item['day']] = $plus[$item['day']] = $maxs[$item['day']] = 0;
            }
            $images[$item['day']] += $item['image_token'];
            if($item['model'] == 'plus'){
                $plus[$item['day']] += $item['text_token'];
            }
            if($item['model'] == 'max'){
                $maxs[$item['day']] = $item['text_token'];
            }
        }
        $chart = amis()->Chart()->height(380)->className('h-96')->config([
            'backgroundColor' => '',
            'title'           => ['text' => '近30天Token数'],
            'tooltip'         => ['trigger' => 'axis'],
            'xAxis'           => [
                'type'        => 'category',
                'boundaryGap' => false,
                'data'        => $days,
            ],
            'yAxis'           => ['type' => 'value'],
            'grid'            => ['left' => '7%', 'right' => '7%', 'top' => 60, 'bottom' => 30,],
            'legend'          => ['data' => ['图片','普通版','高级版']],
            'series'          => [
                [
                    'name'      => '图片',
                    'data'      => array_values($images),
                    'type'      => 'line',
                    'areaStyle' => [],
                    'smooth'    => true,
                    'symbol'    => 'none',
                ],
                [
                    'name'      => '普通版',
                    'data'      => array_values($plus),
                    'type'      => 'line',
                    'areaStyle' => [],
                    'smooth'    => true,
                    'symbol'    => 'none',
                ],
                [
                    'name'      => '高级版',
                    'data'      => array_values($maxs),
                    'type'      => 'line',
                    'areaStyle' => [],
                    'smooth'    => true,
                    'symbol'    => 'none',
                ],
            ],
        ]);

        return amis()->Card()->className('clear-card-mb')->body($chart);
    }

    public function cube()
    {
        return amis()->Card()->className('h-96 ml-4 w-8/12')->body(
            amis()->Html()->html(<<<HTML
<style>
    .cube-box{ height: 300px; display: flex; align-items: center; justify-content: center; }
  .cube { width: 100px; height: 100px; position: relative; transform-style: preserve-3d; animation: rotate 10s linear infinite; }
  .cube:after {
    content: '';
    width: 100%;
    height: 100%;
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.2);
    position: absolute;
    transform-origin: bottom;
    transform-style: preserve-3d;
    transform: rotateX(90deg) translateY(50px) translateZ(-50px);
    background-color: rgba(0, 0, 0, 0.1);
  }
  .cube div {
    background-color: rgba(64, 158, 255, 0.7);
    position: absolute;
    width: 100%;
    height: 100%;
    border: 1px solid rgb(27, 99, 170);
    box-shadow: 0 0 60px rgba(64, 158, 255, 0.7);
  }
  .cube div:nth-child(1) { transform: translateZ(-50px); animation: shade 10s -5s linear infinite; }
  .cube div:nth-child(2) { transform: translateZ(50px) rotateY(180deg); animation: shade 10s linear infinite; }
  .cube div:nth-child(3) { transform-origin: right; transform: translateZ(50px) rotateY(270deg); animation: shade 10s -2.5s linear infinite; }
  .cube div:nth-child(4) { transform-origin: left; transform: translateZ(50px) rotateY(90deg); animation: shade 10s -7.5s linear infinite; }
  .cube div:nth-child(5) { transform-origin: bottom; transform: translateZ(50px) rotateX(90deg); background-color: rgba(0, 0, 0, 0.7); }
  .cube div:nth-child(6) { transform-origin: top; transform: translateZ(50px) rotateX(270deg); }

  @keyframes rotate {
    0% { transform: rotateX(-15deg) rotateY(0deg); }
    100% { transform: rotateX(-15deg) rotateY(360deg); }
  }
  @keyframes shade { 50% { background-color: rgba(0, 0, 0, 0.7); } }
</style>
<div class="cube-box">
    <div class="cube">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
</div>
HTML

            )
        );
    }

    private function css(): array
    {
        /** @noinspection all */
        return [
            '.clear-card-mb td'                 => [
                'height' => '40px !important',
            ],
            '.cxd-Image'                     => [
                'border' => '0',
            ],
            '.bg-blingbling'                 => [
                'color'             => '#fff',
                'background'        => 'linear-gradient(to bottom right, #2C3E50, #FD746C, #FF8235, #ffff1c, #92FE9D, #00C9FF, #a044ff, #e73827)',
                'background-repeat' => 'no-repeat',
                'background-size'   => '1000% 1000%',
                'animation'         => 'gradient 60s ease infinite',
            ],
            '@keyframes gradient'            => [
                '0%{background-position:0% 0%} 50%{background-position:100% 100%} 100%{background-position:0% 0%}',
            ],
            '.bg-blingbling .cxd-Card-title' => [
                'color' => '#fff',
            ],
        ];
    }
}
